//
//  KeyBoardView.m
//  Keyboard
//
//  Created by  ios－hs on 15/6/3.
//  Copyright (c) 2015年  ios－hs. All rights reserved.
//

#import "KeyBoardView.h"
#import "UIView+frame.h"

#define DELETETAG 980
#define OKTAG 981
#define CLEANTAG 982
#define GANGTAG 983
#define AOTAG 984
#define CITYBTNTAG 100
#define NUMBTNTAG 200


@implementation KeyBoardView
{
    NSDictionary * _dict;
    
    // 数据Array
    NSArray * _cityArray;
    NSArray * _charArray;
    
    // View
    UIView * _cityView;
    UIView * _charView;
    
    NSMutableArray *_resultArray;
    UIToolbar *_toolbar;
}


// 初始化方法
- (instancetype)initWithFrame:(CGRect)frame defaultString:(NSString *)defaultString
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor whiteColor];
        
        _cityArray = [[NSArray alloc]init];
        _charArray = [[NSArray alloc]init];
        
        _toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.width, 40)];
        UIBarButtonItem *itm = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"carNo_tap.png"] style:UIBarButtonItemStylePlain target:self action:@selector(hidenKB)];
        itm.tintColor = kHexColor(0x787878);
        
        UIBarButtonItem *sp = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        _toolbar.items = @[sp,itm,sp];
        
        _cityView = [[UIView alloc]initWithFrame:CGRectMake(0, _toolbar.maxY, self.width, self.height - _toolbar.maxY)];
        _charView = [[UIView alloc]initWithFrame:CGRectMake(0, _toolbar.maxY, self.width, self.height - _toolbar.maxY)];
        _cityView.userInteractionEnabled = YES;
        
        [self addSubview:_toolbar];
        [self addSubview:_cityView];
        [self addSubview:_charView];
        
        NSString * path = [[NSBundle mainBundle]pathForResource:@"CarNoList" ofType:@"plist"];
        _dict = [[NSDictionary alloc]initWithContentsOfFile:path];
        
        _cityArray = [_dict objectForKey:@"textList"];
        _charArray = [_dict objectForKey:@"numberList"];
        
        _index = defaultString.length;
        
        [self reloadResultStringWithString:defaultString];
        
        [self setCityView];
        [self setCharView];
        [self isCityViewORCharView];
        
    }
    return self;
}

- (void)reloadResultStringWithString:(NSString *)string{
    _effectiveNum = 0;
    _resultArray = [NSMutableArray array];
    for (int i = 0; i < 8;i++) {
        if (i < string.length) {
            NSString *str = [string substringWithRange:NSMakeRange(i, 1)];
            
            if (!([str isEqualToString:@""] || [str isEqualToString:@" "])) {
                _effectiveNum ++;
                _index = i;
            }
            
            [_resultArray addObject:str];
            
        }else{
            [_resultArray addObject:@" "];
        }
        
    }
}


- (void)setIndex:(NSInteger)index{
    _index = index;
    [self isCityViewORCharView];
    
    if (_block) {
        _block([self getResultString],@"");
    }
}

#pragma mark - 判断是省份选择界面还是数字与字母选择界面
- (void)isCityViewORCharView
{
    if (_index == 0) {
        [_cityView setHidden:NO];
        [_charView setHidden:YES];
        return;
    }else
    {
        [_cityView setHidden:YES];
        [_charView setHidden:NO];
    }
    
    UIButton *buttonI = [self viewWithTag:NUMBTNTAG + 17];//I
    UIButton *buttonO = [self viewWithTag:NUMBTNTAG + 18];//O
    UIButton *buttonG = [self viewWithTag:GANGTAG];//港
    UIButton *buttonAO = [self viewWithTag:AOTAG];//澳

    if(_index != 1){//在其他位置不能输入字符I和O
        [buttonI setTitleColor:kHexColor(0xc3c3c3) forState:(UIControlStateNormal)];
        [buttonO setTitleColor:kHexColor(0xc3c3c3) forState:(UIControlStateNormal)];
        buttonI.layer.borderColor = kHexColor(0xc3c3c3).CGColor;
        buttonO.layer.borderColor = kHexColor(0xc3c3c3).CGColor;
        
        buttonI.userInteractionEnabled = NO;
        buttonO.userInteractionEnabled = NO;

    }else{
        [buttonI setTitleColor:kHexColor(0x787878) forState:(UIControlStateNormal)];
        [buttonO setTitleColor:kHexColor(0x787878) forState:(UIControlStateNormal)];
        buttonI.layer.borderColor = kHexColor(0x787878).CGColor;
        buttonO.layer.borderColor = kHexColor(0x787878).CGColor;

        buttonI.userInteractionEnabled = YES;
        buttonO.userInteractionEnabled = YES;
    }
    
    if (_index != 6) {
        [buttonG setTitleColor:kHexColor(0xc3c3c3) forState:(UIControlStateNormal)];
        [buttonAO setTitleColor:kHexColor(0xc3c3c3) forState:(UIControlStateNormal)];
        buttonG.layer.borderColor = kHexColor(0xc3c3c3).CGColor;
        buttonAO.layer.borderColor = kHexColor(0xc3c3c3).CGColor;
        
        buttonG.userInteractionEnabled = NO;
        buttonAO.userInteractionEnabled = NO;
    }else{
        
        [buttonG setTitleColor:kHexColor(0x787878) forState:(UIControlStateNormal)];
        [buttonAO setTitleColor:kHexColor(0x787878) forState:(UIControlStateNormal)];
        buttonG.layer.borderColor = kHexColor(0x787878).CGColor;
        buttonAO.layer.borderColor = kHexColor(0x787878).CGColor;
        buttonG.userInteractionEnabled = YES;
        buttonAO.userInteractionEnabled = YES ;

    }
}

#pragma mark - 省份选择View
- (void)setCityView
{
    for (int j = 0; j < 4; j++) {
        for (int i = 0 ; i < 8; i++) {
            
            if(j ==3 && i == 8){
                continue;
            }
            
            CGFloat edge = 5;
            CGFloat btnW = (self.width - edge * 9)/8.0;
            
            UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
            
            button.frame = CGRectMake(btnW * i + (i+1) * edge,btnW * j + (j+1) * edge,btnW,btnW);
            button.layer.masksToBounds = YES;
            button.layer.cornerRadius = btnW/2.0;
            button.layer.borderColor = kHexColor(0x787878).CGColor;
            button.layer.borderWidth = 1;
            
            [button setBackgroundColor:[UIColor whiteColor]];
            
            [button setTitleColor: kHexColor(0x787878) forState:UIControlStateNormal];
            
            NSString *title = _cityArray[j * 8 + i];
            [button setTitle:title forState:(UIControlStateNormal)];
            button.titleLabel.adjustsFontSizeToFitWidth = YES;
            
            button.tag = CITYBTNTAG + j * 8 + i;

            [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            
            [_cityView addSubview:button];
            
        }
    }
}

#pragma mark - 字符选择View
- (void) setCharView
{
    for (int j = 0; j < 4; j++) {
        for (int i = 0 ; i < 10; i++) {
            
            CGFloat edge = 5;
            CGFloat btnW = (self.width - edge * 11) / 10.0;
            
            UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(btnW * i + (i+1) * edge,btnW * j + (j+1) * edge,btnW,btnW);
            
            button.tag = NUMBTNTAG + j * 10 + i;
            [button setBackgroundColor:[UIColor whiteColor]];
            button.layer.masksToBounds = YES;
            button.layer.cornerRadius = 4;
            button.layer.borderWidth = 1;
            button.layer.borderColor = kHexColor(0x787878).CGColor;
            
            NSString *title = _charArray[j * 10 + i];
            [button setTitle:title forState:(UIControlStateNormal)];
            [button setTitleColor:kHexColor(0x787878) forState:UIControlStateNormal];
            button.titleLabel.adjustsFontSizeToFitWidth = YES;
            
            if (j == 0) {//数字
                button.layer.cornerRadius = button.width / 2.0;
            }else if (j == 2 && i== 9) {// 删除按钮
                
                [button setImage:[UIImage imageNamed:@"camaraImage.bundle/carNo_delete.png"] forState:0];
                
                [button addTarget:self action:@selector(delete) forControlEvents:(UIControlEventTouchUpInside)];
                [_charView addSubview:button];
                
                button.tag = DELETETAG;
                
                break;
            }else if (j == 3 && i == 7){//港
                button.tag = GANGTAG;
            }else if (j == 3 && i == 8){//澳
                button.tag = AOTAG;
            }else if (j == 3 && i == 9){//确定
                button.layer.borderColor =  kHexColor(0x2d82d7).CGColor;
                button.backgroundColor = kHexColor(0x2d82d7);
                [button setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
                
                button.tag = OKTAG;
                [button addTarget:self action:@selector(ok) forControlEvents:UIControlEventTouchUpInside];
                [_charView addSubview:button];
                break;
                
            }
            
            [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            
            [_charView addSubview:button];
            
        }
    }

}

#pragma mark ============= 城市 与 数字字符 页面的按钮点击事件 ===============


- (void)buttonAction:(UIButton *)button{
    NSString * blockStr = @" ";

    _maxLength = _maxLength > 0 ? _maxLength : 8;
    
    // 省份部分
    if (button.tag - CITYBTNTAG < _cityArray.count) {
        
        blockStr = _cityArray[button.tag - CITYBTNTAG];
        
    }
    else if ((button.tag >= NUMBTNTAG) && (button.tag < NUMBTNTAG + _charArray.count)) {//  数字与字母部分
        blockStr = _charArray[button.tag-NUMBTNTAG] ;
    }
    
    else if (_index == 6){
        if (button.tag == GANGTAG) {
            blockStr = @"港" ;
        }else if (button.tag == AOTAG) {
            blockStr = @"澳" ;
        }
    }
    
    if (_index == 1 && blockStr.length > 0 && [blockStr characterAtIndex:0] >= '0' && [blockStr characterAtIndex:0] <= '9') {
        //第二位不能输数字
        return;
    }else if ([blockStr isEqualToString:@" "]){//无效输入
        return;
    }else{
        
        if ([_resultArray[_index] isEqualToString:@" "]) {
            ++_effectiveNum;
        }
        
        [_resultArray replaceObjectAtIndex:_index withObject:blockStr];
        
        if (_index < _maxLength - 1) {
            _index ++;
        }
    }
    
    if (_block) {
        
        _block([self getResultString],blockStr);
    }
    [self isCityViewORCharView];
    
    
}

//删除
- (void)delete{
    
    NSString * blockStr = @" ";
    
    if ([_resultArray[_index] isEqualToString:blockStr]) {
        
        _index = _index - 1 > 0 ? --_index  : 0;
    }
    
    [_resultArray replaceObjectAtIndex:_index withObject:@" "];
    
    _effectiveNum = _effectiveNum -1 > 0 ? --_effectiveNum  : 0;
    
    if (_block) {
        _block([self getResultString],@"");
    }
    
    [self isCityViewORCharView];
    
}

//确定
- (void)ok{
    // if (_effectiveNum >= _maxLength) {
    
    if (_okBlock) {
        _okBlock([self getResultString]);
    }
    //}
    
}

//清空
- (void)clean{
    _resultArray = @[@" ",@" ",@" ",@" ",@" ",@" ",@" ",@" "].mutableCopy;
    
    _index = 0;
    _effectiveNum = 0;
    
    if (_block) {
        _block([self getResultString],@"");
    }
    
    [self isCityViewORCharView];
}

- (NSString *)getResultString{
    
    NSMutableString *string = [NSMutableString string];
    for (int i = 0; i < _maxLength; i++) {
        [string appendString:_resultArray[i]];
    }
    
    return string;
}

- (void)hidenKB{
    [self removeFromSuperview];
    if (_removeKeyBoardViewBlock) {
        _removeKeyBoardViewBlock();
    }
}

@end
